package com.topone.permission.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import com.topone.Exception.FanZoneException;
import com.topone.permission.dao.RoleAndPermissionMapper;
import com.topone.permission.dao.RoleMapper;
import com.topone.permission.entity.Permission;
import com.topone.permission.entity.Role;
import com.topone.permission.entity.RoleAndPermission;


@Service
public class RoleService {
	
	@Autowired
	RoleMapper roleMapper;
	
	@Autowired
	RoleAndPermissionMapper roleAndPermissionMapper;
	
	
	/**
	 * 查询某一个用所拥有角色
	 * @param userId
	 * @return
	 */
	public List<Role> findByUserId(Long userId){
		Assert.notNull(userId,"The userId is null");
		List<Role> list = roleMapper.findByUserId(userId);
		return list;
	}

	/**
	 * 查询某一个企业的所有的角色包括系统角色以及权限
	 * @param bussionId
	 * @return
	 */
	public List<Role> findByCompanyCodeContainSystemRole(String bcompanyCode,String systermCode){
		Assert.hasText(bcompanyCode,"The bussionId is null");
		return	roleMapper.findByCompanyCodeContainSystemRole(bcompanyCode,systermCode);
	}
	

	/**
	 * 创建角色
	 * @param role
	 */
	@Transactional
	public void save(Role role){
		Assert.notNull(role, "The role is null");
		role.setIsPrivilege("0");
		roleMapper.save(role);
		if(!CollectionUtils.isEmpty(role.getPermissions())){
			relationship(role);
		}
		
	}
	
	/**
	 * 更新角色
	 * 当permissions不为空时，会更新role和perssion的中间表
	 * @param role
	 * @return
	 */
	@Transactional
	public void edit(Role role,String companyCode){
		Assert.notNull(role, "The role is null");
		Assert.notNull(companyCode, "The companyCode is null");
		Role oldRole = findByRoleId(role.getId());
		if("1".equals(oldRole.getIsPrivilege())){
			throw new FanZoneException(5000,"非法修改！");
		}
		role.setIsPrivilege("0");
		if(companyCode.equals(oldRole.getCompanyCode())){
			relationship(role);
		}else{
			throw new FanZoneException(5000,"非法修改！");
		}
		
	}
	
	public Role findByRoleId(Long id) {
		Assert.notNull(id, "The roleId is null");
		return roleMapper.findById(id);
	}

	private void relationship(Role role){
		Assert.notNull(role, "The role is null");
		if(!CollectionUtils.isEmpty(role.getPermissions())){
			List<RoleAndPermission> list=new ArrayList<>();
			for (Permission permission : role.getPermissions()) {
				RoleAndPermission rp = new RoleAndPermission();
				rp.setPermissionId(permission.getParentId());
				rp.setRoleId(role.getId());
			}
			if(!CollectionUtils.isEmpty(list)){
				roleAndPermissionMapper.detele(new RoleAndPermission(role.getId()));
				roleAndPermissionMapper.batchsave(list);
			}
		}
	}
	
	
}
